#!/usr/bin/env python  
# encoding: utf-8   

""" 
@version: v1.0 
@author: null 
@software: PyCharm 
@file: __init__.py.py 
@time: 2017.4.29 9:24 
"""

import requests
import time
import re
from bs4 import BeautifulSoup
import simplejson as json
from weibo.url import URL
import weibo.settings as config
import sqlite3
import logging
from weibo.models.browserlogin import *
import weibo.utils as utils

class Model(object):

    def __init__(self, **kwargs):
        self.username = config.username
        self.password = config.password
        self.session = requests.Session()
        self.st=''
        self.jsonobj={}

    def login(self,username, password,proxy):

        if not (username and password):
            self.logger.error("请输入用户名密码")
            return False
        self.username = username
        self.password = password
        post_data = {
            'username': username,
            'password': password,
            'savestate': '1',
            'ec': '0',
            'pagerefer': 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F&wm=3349&vt=4',
            'entry': 'mweibo'
        }
        response = self.session.post(url=URL.login(), data=post_data, headers=config.loginHeaders,proxies=proxy)

        if response.status_code != 200:
            self.logger.error("请求失败，请检查网络")
            return False
        try:
            data = response.json()
        except:
            self.logger.error('登录请求出错')
            return False


        if data.get("msg") == "请输入验证码":
            self.logger.error("使用浏览器尝试登录")
            cookiestr = loginBrowser(self.username, self.password)
            cookieobj = utils.cookieStr2cookieObj(cookiestr)
            self.session.cookies=cookieobj
        jsonstr,self.jsonobj=self.getInfo(proxy)
        try:
            st = self.jsonobj["common"]["st"]
        except:
            self.logger.error("获取st异常")
            return False
        self.st=st
        cookie = utils.cookieObj2cookieStr(self.session.cookies)
        return self.saveCookies(cookie,st,jsonstr)
        pass

    def str2cookie(self,cookiestr):

        pass

    def getInfo(self,proxy):
        mblog = self.session.get(url=URL.index(), headers=config.headers,proxies=proxy).text
        soup = BeautifulSoup(mblog, 'html.parser')
        script = soup.body.find_all("script")
        jsonstr = re.findall("{.+}",script[0].string.split(";")[1])[0].replace("'","\"")
        jsonobj = json.loads(jsonstr)
        return jsonstr,jsonobj

        pass

    def saveCookies(self,cookie,st,jsonstr):

        conn = sqlite3.connect('..\weibo\db\weiboInfo.db')

        try:
            create_tb="CREATE TABLE IF NOT EXISTS userInfo " \
                      "("\
                      "'id'  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"\
                      "'username'  TEXT,"\
                      "'cookie'  TEXT,"\
                      "'st'  TEXT,"\
                      "'json' TEXT,"\
                      "'updatetime'  TEXT"\
                      ");"
            conn.execute(create_tb)
        except:
            self.logger.error("创建数据库失败")
            return False
        formattime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

        select_tb="select * from userInfo WHERE username='"+self.username+"'"
        cursor = conn.execute(select_tb)
        data = cursor.fetchall()
        try:
            if data and data[0][0]!="":
                update_tb = "update userInfo set cookie='%s',st='%s',json='%s',updatetime='%s' WHERE username='%s'" % (
                cookie, st, jsonstr, formattime, self.username)
                conn.execute(update_tb)
            else:
                insert_tb = "insert into userInfo (username,cookie,st,json,updatetime) " \
                            "VALUES  ('%s','%s','%s','%s','%s')" % (self.username, cookie, st, jsonstr, formattime)
                conn.execute(insert_tb)
            conn.commit()
        except Exception as e:
            self.logger.error(e)
            self.logger.error("保存数据库失败")
            conn.close()
            return False
        conn.close()
        return True

        pass

    @property
    def logger(self):
        logger = logging.getLogger(self.__class__.__name__)
        return logging.LoggerAdapter(logger, {'weibo': self})

    def log(self, message, level=logging.INFO, **kw):
        self.logger.log(level, message, **kw)

    # 将response转为json
    def response2json(self, response):
        try:
            data = response.json()
            return data
        except:
            self.logger.error("解析json出错,response错误代码:"+response.status_code)
            return ''

    def get(self,url,header=config.headers,proxy=None):
        response = self.session.get(url=url, headers=header,proxies=proxy)
        return self.response2json(response)
        pass

    def post(self,url,data,header=config.likeHeaders,proxy=None):

        response = self.session.post(url=url, headers=header, data=data,proxies=proxy)
        return self.response2json(response)
        pass